package v1

import (
	"ginTea/model"
	"ginTea/utils/errmsg"
	"net/http"
	"strconv"
	"strings"

	"github.com/gin-gonic/gin"
)

// 查询分类是否存在

// 添加分类
func AddCategory(c *gin.Context) {
	var code int
	var success bool
	var data model.Category
	_ = c.ShouldBindJSON(&data)
	name := strings.TrimSpace(data.Name)
	if len(name) < 1 ||
		len(name) > 20 {
		code = errmsg.ERROR_CATEGORY_DATA_FAIL
		success = false
	} else {
		// 检测分类是否已经存在
		code = model.CheckCategoryExist(data.Name)
		if code == errmsg.SUCCESS {
			//创建分类
			model.CreateCategory(&data)
			success = true
		}
		if code == errmsg.ERROR_CATEGORY_USED {
			code = errmsg.ERROR_CATEGORY_USED
			success = false
		}
	}
	c.JSON(http.StatusOK, gin.H{
		"code":    code,
		"msg":     errmsg.GetErrMsg(code),
		"success": success,
	})
}

// 删除分类
func DeleteCategory(c *gin.Context) {
	var code int
	id, _ := strconv.Atoi(c.Param("id"))
	code = model.DeleteCategory(id)
	c.JSON(http.StatusOK, gin.H{
		"code":    code,
		"msg":     errmsg.GetErrMsg(code),
		"success": true,
	})
}

// 查询单个分类下的商品

// 获取分类列表
func GetCategoryList(c *gin.Context) {
	var code int
	data, total := model.GetCategoryList()
	code = errmsg.SUCCESS
	c.JSON(http.StatusOK, gin.H{
		"code":    code,
		"data":    data,
		"total":   total,
		"msg":     errmsg.GetErrMsg(code),
		"success": true,
	})
}

// 编辑分类
func UpdateCategory(c *gin.Context) {
	var code int
	var data model.Category
	id, _ := strconv.Atoi(c.Param("id"))
	c.ShouldBindJSON(&data)
	code = model.UpdateCategory(id, &data)
	if code == errmsg.ERROR_CATEGORY_USED {
		c.JSON(http.StatusOK, gin.H{
			"code":    code,
			"msg":     errmsg.GetErrMsg(code),
			"success": false,
		})
	} else {
		c.JSON(http.StatusOK, gin.H{
			"code":    code,
			"msg":     errmsg.GetErrMsg(code),
			"success": true,
		})
	}
}
